package net.oschina.simpleplus.dao.impl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import net.oschina.simpleplus.dao.PostDao;
import net.oschina.simpleplus.entity.Post;
import net.oschina.simpleplus.util.ClazzUtil;
import net.oschina.simpleplus.util.StrUtil;
import net.oschina.simpleplus.vo.PostVo;

@Repository
public class PostDaoImpl implements PostDao{

	@Autowired
	private JdbcTemplate jdbcTemplate;

	
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	@Override
	public List<PostVo> findPostsByPage(int page){
		page = Math.max(1, page);
		
		StringBuilder sql = new StringBuilder();
		
		sql.append("SELECT ")
		.append("p.*, u.nick_name, u.head_img")
		.append(" FROM (SELECT * FROM post WHERE post_id = 0 ORDER BY id DESC LIMIT ?,? ) p LEFT JOIN user u ON p.author_id = u.id");
		return jdbcTemplate.query(sql.toString(), new Object[]{20 * (page - 1), 20},  (rs, rowNum) ->{
			return ClazzUtil.extraData(rs, PostVo.class);
		});
	}
	
	
	@Override
	public void insertPost(Post post){
		jdbcTemplate.update("insert into post(create_time, author_id, last_update_time, title, content, post_id)values(?, ?, ?, ?, ?, ?)", 
				new Object[]{
						new Timestamp(post.getCreateTime().getTime()),
						post.getAuthorId(),
						new Timestamp(post.getLastUpdateTime().getTime()),
						post.getTitle(),
						post.getContent(),
						post.getPostId()
								}) ;
	}
	
	
	@Override
	public void batchInsertPost(List<Post> posts){
		StringBuilder sb = new StringBuilder();
		sb.append("insert into post(create_time, author_id, last_update_time, title, content, post_id) values ");
		posts.stream().forEach(post ->{
			sb.append("('").append(sdf.format(post.getCreateTime())).append("',").append(post.getAuthorId()).append(",'")
					.append(sdf.format(post.getLastUpdateTime())).append("','").append(post.getTitle()).append("','")
					.append(post.getContent()).append("',").append(post.getPostId())
			.append("),");
			
			});
		
		jdbcTemplate.update(StrUtil.removeEndIgnoreCase(sb.toString(), ",")) ;
	}


	@Override
	public List<PostVo> findPostsById(int id, int page) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ")
		.append("p.*, u.nick_name, u.head_img")
		.append(" FROM (SELECT * FROM post WHERE post_id = ? OR id = ? ORDER BY id ASC LIMIT ?,? ) p LEFT JOIN user u ON p.author_id = u.id");
		return jdbcTemplate.query(sql.toString(), new Object[]{id, id, 20 * (page - 1), 20},  (rs, rowNum) ->{
			return ClazzUtil.extraData(rs, PostVo.class);
		});
	}
}
